import axios from 'axios'
import router from '@/router'
// import addSignToHeader from './sign'
import { getToken, removeToken } from './auth'
import { logoutAPI } from '@/apis/user'
import { useUserStore } from '@/stores'
import { errorPrompt } from '@/plugins/error'

const instance = axios.create({
  // baseURL: import.meta.env.VITE_APP_URL,
  baseURL: 'http://localhost:8000/',
  timeout: 5000
})

instance.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.token = `Bearer ${token}`
    }

    // return addSignToHeader(config)
    return config
  }, e => {
    return Promise.reject(e)
  }
)


instance.interceptors.response.use(
  res => {

    if (res.data.code == 200) {
      return res.data
    }

    if (res.data.code == 404) {
      router.push('/404')
      return Promise.reject(res.data.msg)
    }

    if (res.data.code == 401) {
      const userStore = useUserStore()
      router.push('/login')
      logoutAPI()
      removeToken()
      userStore.clearUserInfo()
      errorPrompt('登录已过期，请重新登录')
      return res.data
    }

    errorPrompt(res.data.msg) // 调试用
    return Promise.reject(Error(res.data.msg))
  },
  e => {
    return Promise.reject(e)
  }
)

export default instance